import ajax from 'uni-ajax';
import cache from './cached.js'
import { loginInit } from '@/hooks/index.js';
import {
  setToken,
  getToken
} from './auth'

const { login }  = loginInit()

function getBaseUrl() {
  let baseURL = '';

  switch (process.env.NODE_ENV) {
    case 'development':
      if (
        uni.getSystemInfoSync().host && uni.getSystemInfoSync().host.env == 'WeChat'
        || uni.getSystemInfoSync().host === 'KUAISHOU'
      ) {
        baseURL = 'https://api.yuanshang.store';
      } else {
        baseURL = '/api';
      }
      break;
    case 'production':
      baseURL = 'https://api.yuanshang.store';
      break;
  }
  return baseURL;
}

function getInitConfig() {
  console.log('getToken()', getToken())
  const config = {
    baseURL: getBaseUrl(),
    header: {
      Authorization: getToken()
    }
  };
  return config;
}

function showMsg(message) {
  if (this && this.$refs && this.$refs.msgDlg) {
    this.$refs.msgDlg.open({
      message
    });
  } else {
    uni.showModal({
      title: '提示',
      content: message,
      showCancel: false
    });
  }
}

const instance = ajax.create(getInitConfig());

instance.interceptors.request.use(
  config => {
    config.baseURL = getBaseUrl();
    config.header.Authorization = getToken();

    return config;
  },
  error => {
    return Promise.reject(error)
  }
);

instance.interceptors.response.use(
  response => {
    const accessToken = response.header['access_token_v2']
    if (accessToken) {
      setToken(accessToken);
    }

    const { data } = response;
    
    // 未返回data属性
    if (!data) {
      showMsg('无响应数据');
      return Promise.reject({
        data: null
      });
    }

    // code不是 200，部分接口不提示，代码中需要自行处理code
    if (data.code != 200) {
      console.log(`接口报错: ${JSON.stringify(data)}`);
      showMsg(data.message || '未知异常');

      if (data.code == '401') {
        setToken('')
        uni.reLaunch({ url: '/pages/index/index' })
        login()
      }

      return Promise.reject(data);
    }

    return data;
  },
  error => {
    console.log(JSON.stringify(error))
    const message = error.data && error.data.message || error.errMsg || '请求发生错误'
    showMsg(message);
    return Promise.reject(error);
  }
);

instance.upload = function(url, files, filePath, formData, callback) {
  return new Promise(async (resolve, reject) => {
    const uploadTask = uni.uploadFile({
      url: `${getBaseUrl()}${url}`,
      header: {
        Authorization: getToken(),
        // #ifdef APP-PLUS
        'content-type': 'multipart/form-data'
        // #endif
      },
      files,
      filePath,
      // 如果第二个参数是 object 类型则作为 formData 使用
      formData: typeof formData === 'object' ? formData : {},
      complete: res => {
        if (res.statusCode === 200) {
          const result = JSON.parse(res.data);
          if (+result.code !== 200) {
            showMsg(result.message || '未知异常');
            reject(result);
          } else {
            resolve(result);
          }
        } else {
          reject({
            code: res.statusCode,
            message: '网络异常，请重试'
          });
        }
      }
    });

    if (typeof callback === 'function') {
      callback(uploadTask)
    }
  })
}

export default instance;